<template>
    <div class="table store sever_list">
        <div class="crumbs store_title">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>推广区域</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="mainBtn">
            <el-button type="success" @click="changeError">异常</el-button>
        </div>
        <div class="container">
            <el-select style="margin-top: 10px;" @change="timeSelectFn" v-model="searchTime" placeholder="时间类型">
                <el-option label="下单时间" value="ORDERTIME"></el-option>
                <el-option label="操作时间" value="ORERATIONTIME"></el-option>
            </el-select>
            <el-date-picker
                v-model="findStartTimeValue"
                @change="dataSelectFn"
                :picker-options="pickerOptAll"
                type="datetimerange"
                style="margin-bottom: 20px"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
            ></el-date-picker>
            <el-table v-if="activeShow" :data="list" show-summary :summary-method="getSummaries" border style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange">
                <el-table-column prop="city" label="地区" :filters="listCity" :filter-method="filterHandler"></el-table-column>
                <el-table-column prop="dereceiveNum" label="总接收"></el-table-column>
                <el-table-column prop="somereceiveNum" label="已接收"></el-table-column>
                <el-table-column prop="receiveNum" label="未跟踪"></el-table-column>
                <el-table-column prop="tailAfterNum" label="跟踪中"></el-table-column>
                <el-table-column prop="invalidNum" label="无效"></el-table-column>
                <el-table-column prop="addWechatNum" label="加微"></el-table-column>
                <el-table-column prop="errorNum" label="异常"></el-table-column>
                <el-table-column prop="repeatNum" label="重复"></el-table-column>
                <el-table-column prop="rate" label="通过率"></el-table-column>
                <el-table-column prop="rateAll" label="总通过率"></el-table-column>
                <el-table-column label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button size="small" type="primary" @click="bandFn(scope.$index, scope.row)">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination
                    v-if="paginationShow"
                    :current-page.sync="cur_page"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    layout="total, sizes, prev, pager, next"
                    :total="pageNum"
                    :page-sizes="[10, 30, 50]"
                    :page-size="pageSize"
                    :current-page="cur_page"
                ></el-pagination>
            </div>
        </div>
    </div>
</template>

<script>
import { storeAsGet, storeAsPost, storeAsPut } from "../api/api"
import { formatDate } from "../tool/tool"
import { base64, tool_confirm } from "../tool/tool"
export default {
    data() {
        return {
            //时间类型
            searchTime: "ORDERTIME",
            //列表数据
            list: [],
            listCity: [],
            //计算合计成功率的对象
            salcTotalObj: {},
            //分页
            pageNum: null,
            paginationShow: true,
            cur_page: 0,
            pageSize: 10,
            // 查询的id
            spreadId: "",
            activeShow: true,
            findStartTimeValue: "",
            startTime: "",
            endTime: "",
            pickerOptions: {
                shortcuts: [
                    {
                        text: "今天",
                        onClick(picker) {
                            const end = new Date()
                            end.setTime(end.getTime())
                            end.setHours(23)
                            end.setMinutes(59)
                            end.setSeconds(59)
                            console.log(end, 115)
                            end.setTime(end.getTime())
                            const start = new Date()
                            start.setHours(0)
                            start.setMinutes(0)
                            start.setSeconds(0)
                            start.setTime(start.getTime())
                            picker.$emit("pick", [start, end])
                        }
                    },
                    {
                        text: "昨天",
                        onClick(picker) {
                            const end = new Date()
                            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1)
                            end.setHours(23)
                            end.setMinutes(59)
                            end.setSeconds(59)
                            console.log(end, 115)
                            end.setTime(end.getTime())
                            const start = new Date()
                            start.setHours(0)
                            start.setMinutes(0)
                            start.setSeconds(0)
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 1
                            )
                            picker.$emit("pick", [start, end])
                        }
                    },
                    {
                        text: "最近7天",
                        onClick(picker) {
                            const end = new Date()
                            end.setHours(23)
                            end.setMinutes(59)
                            end.setSeconds(59)
                            end.setTime(end.getTime())
                            const start = new Date()
                            start.setHours(0)
                            start.setMinutes(0)
                            start.setSeconds(0)
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 6
                            )
                            picker.$emit("pick", [start, end])
                        }
                    },
                    {
                        text: "最近30天",
                        onClick(picker) {
                            const end = new Date()
                            end.setHours(23)
                            end.setMinutes(59)
                            end.setSeconds(59)
                            end.setTime(end.getTime())
                            const start = new Date()
                            start.setHours(0)
                            start.setMinutes(0)
                            start.setSeconds(0)
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 29
                            )
                            picker.$emit("pick", [start, end])
                        }
                    },
                    {
                        text: "最近90天",
                        onClick(picker) {
                            const end = new Date()
                            end.setHours(23)
                            end.setMinutes(59)
                            end.setSeconds(59)
                            end.setTime(end.getTime())
                            const start = new Date()
                            start.setHours(0)
                            start.setMinutes(0)
                            start.setSeconds(0)
                            start.setTime(
                                start.getTime() - 3600 * 1000 * 24 * 89
                            )
                            picker.$emit("pick", [start, end])
                        }
                    }
                ]
            }
        }
    },
    created() {
        this.dataSelectFn()
        // this.getSpreadList(this.cur_page);
    },
    watch: {
        $route() {
            this.getSpreadList(0)
        }
    },
    computed: {},
    methods: {
        //数据列表
        getSpreadList(curPage) {
            // console.log(formatDate(new Date(), 'yyyy-MM-dd'),"Date()")
            console.log(this.startTime, this.endTime, "89")
            this.paginationShow = false
            this.activeShow = false
            this.$nextTick(function() {
                this.activeShow = true
                this.paginationShow = true
            })
            storeAsGet(
                "promote/area/page/time?page=" +
                    curPage +
                    "&size=" +
                    this.pageSize +
                    "&direction=DESC&propertie=createdTime&startTime=" +
                    this.startTime +
                    "&endTime=" +
                    this.endTime +
                    "&timeType=" +
                    this.searchTime
            )
                .then(res => {
                    console.log(res, "101")
                    // 赋值
                    this.pageNum = res.data.content.page.totalElements
                    this.list = res.data.content.page.content
                    this.salcTotalObj = {
                        addWechatNumAll : 0,
                        dereceiveNumAll : 0,
                        repeatNumAll : 0,
                        errorNumAll : 0,
                        invalidNumAll : 0
                    }

                    Array.prototype.slice.call(this.list).forEach((value, index) => {
                            value.dereceiveNum = value.receiveNum + value.addWechatNum + value.invalidNum + value.tailAfterNum + value.errorNum + value.repeatNum
                            value.somereceiveNum = value.receiveNum + value.addWechatNum + value.invalidNum + value.tailAfterNum
                            let rateMon = value.dereceiveNum - value.repeatNum - value.errorNum - value.invalidNum
                            let ratesMon = value.dereceiveNum - value.repeatNum - value.errorNum
                            
                            this.salcTotalObj.addWechatNumAll += value.addWechatNum
                            this.salcTotalObj.dereceiveNumAll += value.dereceiveNum
                            this.salcTotalObj.repeatNumAll += value.repeatNum
                            this.salcTotalObj.errorNumAll += value.errorNum
                            this.salcTotalObj.invalidNumAll += value.invalidNum

                            if (rateMon == 0 || value.dereceiveNum == 0 || ratesMon == 0) {
                                value.rate = Number(0).toFixed(2) + "%"
                                value.rateAll = Number(0).toFixed(2) + "%"
                            } else {
                                value.rate = Number((value.addWechatNum / (value.dereceiveNum - value.repeatNum - value.errorNum - value.invalidNum)) * 100 ).toFixed(2) + "%"
                                value.rateAll = Number((value.addWechatNum / (value.dereceiveNum - value.repeatNum - value.errorNum)) * 100).toFixed(2) + "%"
                            }
                        })
                    this.listCity = []
                    this.list.map(item => {
                        this.listCity.push({
                            text: item.city,
                            value: item.city
                        })
                    })
                })
                .catch(errors => {
                    this.$message.error(errors.response.data.detail)
                })
        },
        timeSelectFn(val) {
            this.cur_page = 1
            this.searchTime = val
            this.getSpreadList(0)
        },
        dataSelectFn(data) {
            //日期搜索预约列表
            let startTime =
                formatDate(new Date(), "yyyy-MM-dd hh:mm:ss").substring(0, 10) +
                " 00:00:00"
            let endTime =
                formatDate(new Date(), "yyyy-MM-dd hh:mm:ss").substring(0, 10) +
                " 23:59:59"
            if (!data) {
                let data = []
                data[0] = startTime
                data[1] = endTime
                this.startTime = data[0]
                this.endTime = data[1]
                this.findStartTimeValue = data
            } else {
                this.startTime = formatDate(data[0], "yyyy-MM-dd hh:mm:ss")
                this.endTime = formatDate(data[1], "yyyy-MM-dd hh:mm:ss")
            }
            this.cur_page = 1
            this.getSpreadList(0)

            console.log(this.findStartTimeValue, "findStartTimeValue")
        },
        //查看详情
        bandFn(e, val) {
            // console.log(e,val)
            this.$router.push({
                path: "/spread",
                query: {
                    province: val.province,
                    city: val.city
                }
            })
        },
        changeError() {
            this.$router.push("/errorexcel")
        },
        filterHandler(value, row, column) {
            const property = column["property"]
            return row[property] === value
        },
        // 分页导航
        handleCurrentChange(val) {
            console.log(val, 111111)
            this.cur_page = val
            this.getSpreadList(val - 1)
        },
        handleSelectionChange(val) {
            console.log(val, "handleSelectionChange")
            // this.multipleSelection = val;
        },
        handleSizeChange(val) {
            this.pageSize = val
            storeAsGet(
                "promote/area/page/time?page=" +
                    0 +
                    "&size=" +
                    val +
                    "&direction=DESC&propertie=createdTime&startTime=" +
                    this.startTime +
                    "&endTime=" +
                    this.endTime
            )
                .then(res => {
                    console.log(res, "101")
                    // 赋值
                    this.pageNum = res.data.content.page.totalElements
                    this.list = res.data.content.page.content
                    
                    this.salcTotalObj = {
                        addWechatNumAll : 0,
                        dereceiveNumAll : 0,
                        repeatNumAll : 0,
                        errorNumAll : 0,
                        invalidNumAll : 0
                    }

                    Array.prototype.slice
                        .call(this.list)
                        .forEach((value, index) => {
                            //已接收dereceiveNum
                            value.dereceiveNum =
                                value.receiveNum +
                                value.addWechatNum +
                                value.invalidNum +
                                value.tailAfterNum +
                                value.errorNum +
                                value.repeatNum
                            value.somereceiveNum =
                                value.receiveNum +
                                value.addWechatNum +
                                value.invalidNum +
                                value.tailAfterNum
                            let rateMon = value.dereceiveNum - value.invalidNum

                            this.salcTotalObj.addWechatNumAll += value.addWechatNum
                            this.salcTotalObj.dereceiveNumAll += value.dereceiveNum
                            this.salcTotalObj.repeatNumAll += value.repeatNum
                            this.salcTotalObj.errorNumAll += value.errorNum
                            this.salcTotalObj.invalidNumAll += value.invalidNum

                            if (rateMon == 0 || value.dereceiveNum == 0) {
                                value.rate = Number(0).toFixed(2) + "%"
                                value.rateAll = Number(0).toFixed(2) + "%"
                            } else {
                                value.rate =
                                    Number(
                                        (value.addWechatNum /
                                            (value.dereceiveNum -
                                                value.repeatNum -
                                                value.errorNum -
                                                value.invalidNum)) *
                                            100
                                    ).toFixed(2) + "%"
                                value.rateAll =
                                    Number(
                                        (value.addWechatNum /
                                            (value.dereceiveNum -
                                                value.repeatNum -
                                                value.errorNum)) *
                                            100
                                    ).toFixed(2) + "%"
                            }
                        })
                    this.listCity = []
                    this.list.map(item => {
                        this.listCity.push({
                            text: item.city,
                            value: item.city
                        })
                    })
                })
                .catch(errors => {
                    this.$message.error(errors.response.data.detail)
                })
            console.log(val, 111111)
        },
        /* 重写计算总数 */
        getSummaries(param) {
            const { columns, data } = param
            const sums = []
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计"
                    return
                }
                /* 计算成交率的 key 标识 */
                if (column.property == "rate" || column.property == "rateAll") {
                    let totalObj = this.salcTotalObj
                    console.log(totalObj)
                    if(!totalObj){
                        return false
                    }
                    let temp = totalObj.dereceiveNumAll - totalObj.repeatNumAll - totalObj.errorNumAll - totalObj.invalidNumAll
                    let tempAll = totalObj.dereceiveNumAll - totalObj.repeatNumAll - totalObj.errorNumAll
                    if(column.property == "rate"){
                        console.log()
                        if(temp == 0){
                            sums[index] = '0.00%'
                            return 
                        }
                        sums[index] = Number((totalObj.addWechatNumAll / temp) * 100 ).toFixed(2) + "%"
                                
                    }else{
                        if(tempAll == 0){
                            sums[index] = '0.00%'
                            return 
                        }
                        sums[index] = Number((totalObj.addWechatNumAll / tempAll) * 100).toFixed(2) + "%"
                    }
                    return
                }
                const values = data.map(item => Number(item[column.property]))
                if (!values.every(value => isNaN(value))) {
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr)
                        if (!isNaN(value)) {
                            return prev + curr
                        } else {
                            return prev
                        }
                    }, 0)
                    sums[index] += ""
                } else {
                    sums[index] = ""
                }
            })

            return sums
        }
    }
}
</script>

<style scoped>
.store {
    position: relative;
}
.store .store_title {
    height: 40px;
}
.store .store_title div {
    line-height: 40px;
}
.ex_parent > div {
    padding: 0px 10px 10px 0px;
}
</style>
